package cn.tedu._05mvcboot4.common.exception;

import cn.tedu._05mvcboot4.common.response.JsonResult;
import cn.tedu._05mvcboot4.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult dohandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.debug("处理参数校验失败异常：{}",e.getMessage());
        return new JsonResult(StatusCode.VALIDATED_ERROR, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult dohandleConstraintViolationException(ConstraintViolationException e){
        log.debug("处理参数校验失败异常：{}",e.getMessage());
        return new JsonResult(StatusCode.VALIDATED_ERROR, e.getConstraintViolations().iterator().next().getMessage());
    }

}
